package cn.hty.mymsg.api.action.send;


import cn.hty.mymsg.common.constant.AustinConstant;
import cn.hty.mymsg.common.enums.RespStatusEnum;
import cn.hty.mymsg.common.pipeline.BusinessProcess;
import cn.hty.mymsg.common.pipeline.ProcessContext;
import cn.hty.mymsg.common.vo.BasicResultVO;
import cn.hty.mymsg.service.domain.MessageParam;
import cn.hty.mymsg.api.domain.SendTaskModel;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 发送消息前置参数检查
 */
@Slf4j
@Service
public class SendPreCheckAction implements BusinessProcess<SendTaskModel> {

    @Override
    public void process(ProcessContext<SendTaskModel> context) {
        //判断消息模板id和参数是否为空
        Long messageTemplateId = context.getProcessModel().getMessageTemplateId();
        List<MessageParam> messageParamList = context.getProcessModel().getMessageParamList();
        if (CollUtil.isEmpty(messageParamList)|| Objects.isNull(messageTemplateId)){
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS, "模板ID或参数列表为空"));
            return;
        }
        //判断接收者是否为空
        List<MessageParam> resultMessageParamList = messageParamList.stream().filter(messageParam -> !CharSequenceUtil.isBlank(messageParam.getReceiver())).collect(Collectors.toList());
        if (CollUtil.isEmpty(resultMessageParamList)){
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS, "含接受者的参数列表为空"));
            return;
        }
        //判断请求是否大于100
        if (resultMessageParamList.stream().anyMatch(messageParam -> messageParam.getReceiver().split(StrPool.COMMA).length > AustinConstant.BATCH_RECEIVER_SIZE)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.TOO_MANY_RECEIVER));
            return;
        }
        SendTaskModel sendTaskModel = context.getProcessModel();
        sendTaskModel.setMessageParamList(resultMessageParamList);
    }
}
